import java.util.ArrayList;
import java.util.Iterator;

import java.io.CharArrayReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.LineNumberReader;
import java.io.PushbackReader;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class Nodeswriter {
	
	public void write(String file, Classroom classroom) {
		try {
			XMLStreamWriter xmlStreamWriter = null;
			Writer target = new FileWriter(file);
			XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
			xmlStreamWriter = xmlOutputFactory.createXMLStreamWriter(target);
			xmlStreamWriter.writeStartDocument();
			
			// start root
			xmlStreamWriter.writeStartElement("classroom"); 
			xmlStreamWriter.writeAttribute("students", String.valueOf(classroom.getStudents()));
			
			String[] subjects = classroom.getSubjects();
			
			for (int i = 0; i < classroom.getStudents(); i++) {
				Student current = classroom.getStudent(i);
				
				xmlStreamWriter.writeStartElement("student");
				{
					xmlStreamWriter.writeAttribute("nr", current.getNr());
					xmlStreamWriter.writeAttribute("lastname", current.getLastname());
					xmlStreamWriter.writeAttribute("surname", current.getSurname());
					for (int j = 0; j < subjects.length; j++) {
						xmlStreamWriter.writeAttribute(subjects[j], String.valueOf(current.visitsOptSub(j)));
					}
				}
				xmlStreamWriter.writeEndElement();
			}
				
			// finish root
			xmlStreamWriter.writeEndElement();

			// finish doc
			xmlStreamWriter.writeEndDocument();
			xmlStreamWriter.flush();
			xmlStreamWriter.close();
		} catch (XMLStreamException | IOException e) {
			System.out.println(e.getMessage());
		}
	}	
}
